package com.xiaoxiang.auth.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 生成token的工具类
 *
 */
public class JwtUtil {

    // token的请求头
    @Value("${token.header}")
    public static String TOKEN_HEADER = "Authorization";

    // token前缀
    @Value("${token.prefix}")
    public static String TOKEN_PREFIX = "Bearer ";

    // 密钥
    @Value("${token.secret}")
    private static String SECRET = "aynu2022";

    private static String tokenKeyRoleId = "roleId";

    private static String tokenKeyRoleName = "roleName";

    private static String tokenKeyUserId = "userId";

    private static String tokenKeyUsername = "username";


    // 过期时间是3600秒，既是1个小时
    @Value("${token.expire}")
    private static long EXPIRATION = 3600L;


    // 创建token
    public static String createToken(Long userId, List<Long> roleIdList, List<String> roleNameList, String username) {
        HashMap<String, Object> map = new HashMap<>();
        map.put(tokenKeyRoleId, roleIdList);
        map.put(tokenKeyRoleName, roleNameList);
        map.put(tokenKeyUserId, userId);
        map.put(tokenKeyUsername, username);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(map)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .compact();
    }


    // 获取用户角色
    public static List getRoleName(String token) {
        return  (List) getTokenBody(token).get(tokenKeyRoleName);
    }

    // 是否有效
    public static boolean isValid(String token) {
        try {
            getTokenBody(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 是否已过期
    public static boolean isExpiration(String token) {
        try {
            return getTokenBody(token).getExpiration().before(new Date());
        } catch (ExpiredJwtException e) {
            return true;
        }
    }
    // 获取主体内容
    private static Claims getTokenBody(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }
}

